package MainProgram;

import Algorithms.BackPropagation;
import NeuronNetworkLibrary.Network;
import Algorithms.NeuralCrossValidation;
import java.util.Arrays;

/**
 *
 * @author Zbyszko
 */
public class CrossValidationMain {

    public static int EPOCH = 1000;

    static public void main(String[] args) {

        SinusCreator data = new SinusCreator(100);
        //SimpleDataCreator data = new SimpleDataCreator();
        // Create and build the network.
        Network network = new Network(data.getTrainingSet(), data.getDesiredOutput(),
                new int[]{1}, new String[]{"sigmo"}, "linear");
        NeuralCrossValidation NSV = new NeuralCrossValidation(network);

        int iterator = 1;
        double minValue = Double.MAX_VALUE;
        int neurons = 0;
 
        
        while (iterator < 16) {

            for (int i = 0; i < 100; i++) {
                NSV.performCrossValidation();
            }
            iterator++;
            network.setNeuronsInHiddenLayers(new int[]{iterator});
            if(NSV.getError() < minValue) {
                minValue = NSV.getError();
                neurons = iterator;
            }
            System.out.println("error: " + NSV.getError());
        }

        System.out.println("min-neurons: " + neurons);
//        network.setTrainingSet(data.getTrainingSet());
//        network.setDesiredOutputs(data.getDesiredOutput());
//        network.setNeuronsInHiddenLayers(new int[]{neurons});
//        network.updateNumberOfPatterns();
        Network.INIT_WEIGHTS_FLAG = true;
        Network network2 = new Network(data.getTrainingSet(), data.getDesiredOutput(),
                new int[]{neurons}, new String[]{"sigmo"}, "linear");
        
        int j=0;
        int order[];
        
        while(j<EPOCH){
            order = Main.randomizeOrder(network2.getNumberOfPatterns());
            for (int k = 0; k < network2.getNumberOfPatterns(); k++) {
                // Calculate forwardly the network outputs.
                network2.calculateNetwork(order[k]);
                // Use Backpropagation algorithm to change the weights. 
                BackPropagation.calculateBackPropagation(network2);
            }
            j++;
        }

        // Show plot
        String units = Arrays.toString(network2.getNeuronsInHiddenLayers());
        //System.out.println("bbb");
        Plot plot = new Plot(
                "Neural Network", //window title 
                "Cross validation with " + units + " hidden neurons", //plot title
                data.getTrainingSet(), //training set 
                data.getDesiredOutput(), //desired output
                network2.getTrainingSet(),
                Main.printFinalResults(network2) //obtained result
                );
        plot.setVisible(true);
//        //*/
                        ;
    }
}
